//
//  HomeView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/6/19.
//

import SwiftUI

struct HomeView: View {
    
    @EnvironmentObject var appState: AppState
    @StateObject var viewModel = HomeVM()
    @EnvironmentObject private var store: CardStore
    
    @State var orderedCards: [SignType] = []
    
    var visibleCards: [SignType] {
        if let headerIndex = orderedCards.firstIndex(of: .header) {
            return Array(orderedCards.prefix(upTo: headerIndex))
        } else {
            return orderedCards
        }
    }
    
    var body: some View {
        ZStack(alignment: .top) {
            Color(hex: "#0A0A0A")
                .ignoresSafeArea()
                .ignoresSafeArea()
            ScrollView {
                VStack(alignment: .center, spacing: 0) {
                    if appState.currentDevice != nil {
                        HStack(spacing: 0) {
                            Image("6623")
                                .frame(width: 24,height: 24)
                            Text(viewModel.currentWatch)
                                .font(.system(size: 16, weight: .medium))
                                .foregroundColor(.white)
                                .padding(.leading, 6)
                            Spacer()
                            Button(action: {
                            }) {
                                Text("切换设备")
                                    .font(.system(size: 12, weight: .regular))
                                    .foregroundColor(mainColor)
                                    .frame(width: 64, height: 28)
                                    .background(
                                        RoundedRectangle(cornerRadius: 15)
                                            .stroke(mainColor, lineWidth: 0.5)
                                    )
                                    .padding(.leading, 20)
                            }
                        }
                        .frame(height: 40)
                        .padding(.horizontal, 12)
                    } else {
                        ZStack {
                            Color(hex: "1A1A1A").opacity(0.8)
                                .frame(height: 52)
                                .cornerRadius(16, corners: .allCorners)
                            HStack(alignment: .center, spacing: 6) {
                                Image(systemName: "exclamationmark.circle")
                                    .frame(width: 18, height: 18)
                                    .foregroundColor(Color(hex: "#EF5F5F"))
                                Text("你还没有绑定设备")
                                    .font(.system(size: 14, weight: .regular))
                                    .foregroundColor(.white)
                                Spacer()
                                Button(action: {
                                    appState.navigateTo(.scanDevice)
                                }) {
                                    Text("去绑定设备")
                                        .font(.system(size: 12, weight: .regular))
                                        .foregroundColor(mainColor)
                                        .frame(width: 76, height: 28)
                                        .background(
                                            RoundedRectangle(cornerRadius: 15)
                                                .stroke(mainColor, lineWidth: 0.5)
                                        )
                                        .padding(.leading, 20)
                                }
                            }
                            .padding(.horizontal, 12)
                        }
                        .padding(.horizontal, 16)
                    }
                    
                    ZStack(alignment: .bottom) {
                        Image("home_watch_bg")
                            .resizable()
                            .scaledToFill()
                            .frame(width: 194, height: 189)
                            .padding(.bottom, 6)
                        ZStack {
                            Color(hex: "1A1A1A").opacity(0.8)
                                .cornerRadius(16, corners: .allCorners)
                                .padding(.horizontal, 16)
                            HStack(spacing: 0) {
                                Spacer()
                                VStack(alignment: .leading, spacing: 10) {
                                    HStack(spacing: 2) {
                                        Image("step_icon")
                                            .resizable()
                                            .scaledToFill()
                                            .frame(width: 16, height: 16)
                                        Text("步数")
                                            .font(.system(size: 14, weight: .regular))
                                            .foregroundColor(.white)
                                    }
                                    Text("\(viewModel.steps)")
                                        .font(.system(size: 20, weight: .bold))
                                        .foregroundColor(.white)
                                    Text("/\(viewModel.targetSteps)步")
                                        .font(.system(size: 14, weight: .regular))
                                        .foregroundColor(.white)
                                }
                                Spacer()
                                Color(hex: "#F5F5F5")
                                    .frame(width: 1, height: 40)
                                Spacer()
                                VStack(alignment: .leading, spacing: 10) {
                                    HStack(spacing: 2) {
                                        Image("ka_icon")
                                            .resizable()
                                            .scaledToFill()
                                            .frame(width: 16, height: 16)
                                        Text("卡路里")
                                            .font(.system(size: 14, weight: .regular))
                                            .foregroundColor(.white)
                                    }
                                    Text("\(viewModel.ka)")
                                        .font(.system(size: 20, weight: .bold))
                                        .foregroundColor(.white)
                                    Text("/\(viewModel.targetKa)千卡")
                                        .font(.system(size: 14, weight: .regular))
                                        .foregroundColor(.white)
                                }
                                Spacer()
                                Color(hex: "#F5F5F5")
                                    .frame(width: 1, height: 40)
                                Spacer()
                                VStack(alignment: .leading, spacing: 10) {
                                    HStack(spacing: 2) {
                                        Image("time_icon")
                                            .resizable()
                                            .scaledToFill()
                                            .frame(width: 16, height: 16)
                                        Text("距离")
                                            .font(.system(size: 14, weight: .regular))
                                            .foregroundColor(.white)
                                    }
                                    Text("\(viewModel.distance)")
                                        .font(.system(size: 20, weight: .bold))
                                        .foregroundColor(.white)
                                    Text("/\(viewModel.targetDistance)米")
                                        .font(.system(size: 14, weight: .regular))
                                        .foregroundColor(.white)
                                }
                                Spacer()
                            }
                            .padding(.horizontal, 16)
                        }
                        .frame(height: 107)
                        
                    }
                    .frame(height: 195)
                    
                    HeartRateCardView()
                    
                    LazyVGrid(columns: [
                        GridItem(.flexible(), spacing: 12),
                        GridItem(.flexible(), spacing: 12)
                    ], spacing: 12) {
                        ForEach(visibleCards, id: \.self) { card in
                            switch card {
                            case .spo2:
                                Spo2CardView(date: "4月8日 21:53", value: "93%")
                                    .onTapGesture {
                                        appState.navigateTo(.bloodOxygenDetail)
                                    }
                            case .sleep:
                                SleepCardView(quality: "良好", date: "4月8日 22：00-4月9日 05：32")
                                    .onTapGesture {
                                        appState.navigateTo(.sleepQualityDetail)
                                    }
                            case .weight:
                                WeightCardView(value: "68.5kg", date: "4月9日 07：30")
                                    .onTapGesture {
                                        appState.navigateTo(.weightDetail)
                                    }
                            case .pressure:
                                PressureCardView(value: "45", level: "轻度压力", date: "4月9日 10：15")
                                    .onTapGesture {
                                        appState.navigateTo(.stressDetail)
                                    }
                            case .drinkWaterReminder:
                                DrinkCardView(value: "93%", date: "4月9日 10：15")
                                    .onTapGesture {
                                        appState.navigateTo(.drinkReminder)
                                    }
                            case .physiologicalCycle:
                                EmptyView()
                            case .header:
                                EmptyView()
                            }
                        }
                    }
                    .padding(.top, 18)
                    .padding(.horizontal, 16)
                    
                    Button(action: {
                        appState.navigateTo(.cardEdit)
                    }, label: {
                        HStack(alignment: .center, spacing: 0) {
                            Text("编辑数据卡片")
                                .font(.system(size: 16))
                                .foregroundColor(Color(hex: "#242424"))
                            Image("arrow_right_black")
                                .frame(width: 14, height: 14)
                                .scaledToFit()
                        }
                        .frame(height: 40)
                        .frame(maxWidth: .infinity, alignment: .center)
                        .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 26.0)
                    })
                    .padding(.top, 20)
                    .padding(.bottom, 20)
                    .padding(.horizontal, 66)
                }
            }
            
        }
        .fullScreenCover(isPresented: $viewModel.showOnboarding) {
            VStack(spacing: 0) {
                Spacer()
                OnboardingView(showOnboarding: $viewModel.showOnboarding)
                    .frame(height: 544)
                    .cornerRadius(16, corners: [.topLeft, .topRight])
            }
            .interactiveDismissDisabled()
            .background(Color(hex: "#0A0A0A"))
            .ignoresSafeArea()
        }
        .onAppear() {
            UserDefaults.standard.set(true, forKey: disShowOnboarding)
            orderedCards = store.orderedCards
        }
        .onChange(of: store.orderedCards) {
            orderedCards = $0
        }
            
    }
}


//#Preview {
//    HomeView()
//}
